<?php
declare(strict_types = 1);

namespace Tool\Query;

use Swoft\Db\Query\Builder;
use Tool\DB;
use Tool\Pool;
use Swoft\Bean\Annotation\Mapping\Bean;

/**
 * @Bean(scope=Bean::PROTOTYPE)
 * @author mg
 */
class EBuilder extends Builder
{
	/**
	 * New builder instance
	 *
	 * @param mixed ...$params
	 *
	 * @return PrototypeInterface|Builder
	 * @throws DbException
	 */
	public static function new(...$params)
	{
		/**
		 * @var string|null    $poolName
		 * @var Grammar|null   $grammar
		 * @var Processor|null $processor
		 */
		if (empty($params)) {
			$poolName  = Pool::DEFAULT_POOL;
			$grammar   = null;
			$processor = null;
		} else {
			[$poolName, $grammar, $processor] = $params;
		}
		
		$self = self::__instance();
		
		$self->poolName = $poolName;
		$self->setQueryGrammarAndPostProcessor($grammar, $processor);
		
		return $self;
	}
	/**
	 * Get the database connection instance.
	 *
	 * @return Connection
	 * @throws DbException
	 */
	public function getConnection()
	{
		$connection = DB::connection($this->poolName);
		// Select db name
		if (!empty($this->db)) {
			$connection->db($this->db);
		}
		
		return $connection;
	}
}